<?php
require 'TVB/pms/pdes/common/bootstrap.php';

$query  =	empty($_REQUEST['q'])	?	''	:	$_REQUEST['q'];
$type	=	empty($_REQUEST['type']) ?	''	:	$_REQUEST['type'];

$query_string = array('title_en'=>'',      'title_cn'=>'',      'path'=>'',     'id'=>'');
$field_array  = array('title_en'=>'en.title', 'title_cn'=>'cn.title', 'path'=>'p.path', 'id'=>'p.id');

if(isset($query_string[$type])){
	if('id' == $type){
		$query = (int)$query;
		$query_string[$type] = ' AND id = :query';
	}else{
		$query = str_replace("\\", "\\\\", $query);
		$query = "%$query%";
		$query_string[$type] = ' AND '.$field_array[$type].' LIKE :query';
	}
}else{
	exit('[]');
}

$sql = "
	SELECT 
		p.id, cn.title AS title_cn, en.title AS title_en, p.path, '$type' AS 'type' 
	FROM programme p LEFT JOIN
		(SELECT title,programme_id FROM `programme-language` WHERE language_id=:en)AS en ON p.id=en.programme_id LEFT JOIN
		(SELECT title,programme_id FROM `programme-language` WHERE language_id=:cn)AS cn ON p.id=cn.programme_id
	WHERE (en.title IS NOT NULL OR cn.title IS NOT NULL)
		{$query_string['path']} {$query_string['id']} {$query_string['title_en']} {$query_string['title_cn']}
	LIMIT 20
";
$params = array(
	':en'=>language::getLanguageID(AC::LANGUAGE_EN),
	':cn'=>language::getLanguageID(AC::LANGUAGE_ZH),
	':query'=>$query
);
$result	= Model::selectBySql($sql,$params);
foreach($result as &$row){
	$row['eps'] = array();
	$episode_ids = Model::selectBySql(
		'select onair_episode_no from episode where programme_id = :id and status<>:st',
		array(':id'=>$row['id'],':st'=>AC::STATUS_DELETED)
	);
	foreach($episode_ids as $episode_id){
		$row['eps'][] = $episode_id['onair_episode_no'];
	}
}
//var_dump($result);
echo json_encode($result);
